import logging

from django.db.models.signals import post_save
from django.dispatch import receiver

from basic_info.models import WarehouseModel
from goods_info.models import GoodsModel, GoodsInventoryModel

logger = logging.getLogger('erp')
methods = {
    'POST': '新增',
    'DELETE': '删',
    'PUT': '改',
    'PATCH': '改局部',
    'GET': '查'
}


# sender：发送信号的人
# instance: 代表当前正在新增的menu对象
@receiver(post_save, sender=WarehouseModel)
def create_goods_inventory(sender, instance, created, **kwargs):
    """
    创建信号监控函数，
    信号接收者收到之后自动触发。
    创建新仓库之后，给所有的货品在当前新仓库中，新增库存数据，默认所有货品在新仓库中的库存全部为0
    """

    if created:
        logger.info('创建当前新仓库的所有库存数据--每种货品都要插入对应的库存记录')
        if isinstance(instance, WarehouseModel):
            # 先获取所有货品的ID
            ids = GoodsModel.objects.values_list('id', flat=True).all()
            # 批量插入库存记录数据
            inventory_list = []
            for goods_id in ids:
                inventory_list.append(
                    GoodsInventoryModel(goods_id=goods_id, warehouse_id=instance.id, warehouse_name=instance.name)
                )
            # 批量新增的函数：bulk_create
            GoodsInventoryModel.objects.bulk_create(inventory_list)
        else:
            logger.warning('不是WarehouseModel类型，所以不需要创建库存数据！')
